package com.cloud.picture.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.cloud.picture.model.enums.ErrorCodeEnum;
import com.cloud.picture.utils.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.cloud.picture.constant.FileConstants.FILE_TYPES_LIMIT;
import static com.cloud.picture.constant.FileConstants.FILE_UPLOAD_SIZE_LIMIT;

/**
 * @author syf
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate{
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected String validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCodeEnum.PARAMS_ERROR, "上传文件不能为空");
        // 1. 校验文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > FILE_UPLOAD_SIZE_LIMIT, ErrorCodeEnum.PARAMS_ERROR, "文件大小不能超过"+ FILE_UPLOAD_SIZE_LIMIT / 1024 / 1024 + "MB");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!FILE_TYPES_LIMIT.contains(fileSuffix), ErrorCodeEnum.PARAMS_ERROR, "不支持的文件类型");
        return "";
    }
}
